from common import *
import tkinter as tk
from tkinter import ttk, messagebox
from entity.Config import *


class RunConfig(Window):
    def __init__(self, ddt):
        super().__init__()
        self.root = ddt
        self.window = ddt.run_config
        self.title = "运行配置导向"
        self.WIDTH = 0
        self.HEIGHT = 0

        """变量"""
        # dom
        self.jump_window = None
        self.jump_dom = None
        self.name_combobox = None
        # 场景名
        self.name = tk.StringVar()
        self.delay_time = tk.StringVar()
        self.out_time = tk.StringVar()
        self.order_number = 1
        self.scene_list = [path.name for path in self.root.get_scene()]
        # 特征列表
        self.jpgs = None
        # 跳转字典
        self.jump_dict = {}

        """加载组件"""
        self.set_window()
        self.window.title(f"运行顺序-{self.order_number}")

    def set_jpgs(self, event):
        """设置特征列表"""
        self.jpgs = [path.name.split(".")[0] for path in self.get_jpgs()]
        if self.jump_window is not None:
            self.jump_dom.jpg_combobox["value"] = self.jpgs

    def next(self):
        """下一步，保存至内存"""
        _dict = {
            "id": self.order_number,
            "name": self.name.get(),
            "delay_time": self.delay_time.get(),
            "out_time": self.out_time.get(),
            "jump": self.jump_dict
        }
        self.scene_list.pop(self.scene_list.index(self.name.get()))
        self.name_combobox["value"] = self.scene_list
        self.name.set("")
        self.order_number += 1
        self.root.project.config.run_order.append(_dict)
        self.jump_dict = {}
        self.window.title(f"运行顺序-{self.order_number}")
        if self.order_number > len(self.root.get_scene()):
            self.root.info_log("运行配置信息已完成！现在可以按F10运行项目，或许在配置文件中去快速修改运行配置")
            self.exit(True)
            return 0

    def set_run_config(self):
        """配置运行导向"""
        name_label = tk.Label(self.window, text="场景名")
        self.name_combobox = ttk.Combobox(self.window, values=self.scene_list, textvariable=self.name, state="readonly")
        self.name_combobox.bind("<<ComboboxSelected>>", self.set_jpgs)
        delay_label = tk.Label(self.window, text="延迟(秒)")
        delay_entry = tk.Entry(self.window, textvariable=self.delay_time)
        out_label = tk.Label(self.window, text="超时(分)")
        out_entry = tk.Entry(self.window, textvariable=self.out_time)
        jump_button = tk.Button(self.window, text="跳转字典", command=self.set_jump)
        next_button = tk.Button(self.window, text="下一步", command=self.next)

        name_label.grid(row=0, column=0)
        self.name_combobox.grid(row=0, column=1)
        delay_label.grid(row=1, column=0)
        delay_entry.grid(row=1, column=1)
        out_label.grid(row=2, column=0)
        out_entry.grid(row=2, column=1)
        jump_button.grid(row=3, column=0)
        next_button.grid(row=3, column=1)

    def set_jump(self):
        """选择jump界面"""
        if self.jump_window is None:
            if self.name.get() == "":
                messagebox.showwarning("提示", "还没有选择场景，无法获取特征列表")
                return 0
            self.jump_window = tk.Toplevel()
            self.jump_dom = Jump(self)
            self.hide()
            return 0
        self.hide()
        self.jump_dom.show()

    def set_function(self):
        """重写方法"""
        # 窗口置顶弹出
        self.window.wm_attributes('-topmost', 1)
        # 禁止拉伸
        self.window.resizable(0, 0)
        # 去掉窗口最大化最小化按钮，只保留关闭
        self.window.attributes("-toolwindow", 2)
        # 配置导向
        self.set_run_config()

        """绑定事件"""
        # 窗口关闭事件
        self.window.protocol("WM_DELETE_WINDOW", self.exit)

    def exit(self, complete=False):
        self.root.show()
        self.window.destroy()
        try:
            self.jump_window.destroy()
        except AttributeError:
            return 0
        if complete:
            self.root.project.config.save()
            return 1
        self.root.warn_log("中途退出，未持久化配置信息")

    def get_jpgs(self):
        """获取场景下的所有jpg结尾的特征"""
        _list = []
        scene = self.root.project.project / self.name.get()
        for i in scene.rglob("*.jpg"):
            if i.is_file():
                _list.append(i)
        return _list


class Jump(Window):
    def __init__(self, root):
        super().__init__()
        self.root = root
        self.window = root.jump_window
        self.title = "添加跳转"
        self.WIDTH = 0
        self.HEIGHT = 0

        """变量"""
        self.jpg = tk.StringVar()
        self.scene = tk.StringVar()
        self.jpg_combobox = None

        """加载组件"""
        self.set_window()

    def add(self):
        """添加操作"""
        if self.jpg.get() in self.root.jump_dict:
            if not messagebox.askyesno("提示", "该特征已有跳转，是否覆盖原跳转？"):
                return 0
        self.root.jump_dict[self.jpg.get()] = self.scene.get()
        self.jpg.set("")
        self.scene.set("")
        self.exit()

    def set_jpg_to_dir(self):
        """选择跳转界面"""
        jpg_label = tk.Label(self.window, text="特征")
        self.jpg_combobox = ttk.Combobox(self.window, values=self.root.jpgs, textvariable=self.jpg, state="readonly")
        scene_label = tk.Label(self.window, text="跳转至")
        _scene = [path.name for path in self.root.root.get_scene()]
        _scene.extend(["正常终止", "异常终止"])
        scene_combobox = ttk.Combobox(self.window, values=_scene, textvariable=self.scene, state="readonly")
        add_button = tk.Button(self.window, text="添加", command=self.add)
        jpg_label.grid(row=0, column=0)
        self.jpg_combobox.grid(row=0, column=1)
        scene_label.grid(row=1, column=0)
        scene_combobox.grid(row=1, column=1)
        add_button.grid(row=2, column=0, columnspan=2)

    def set_function(self):
        """重写方法"""
        # 窗口置顶弹出
        self.window.wm_attributes('-topmost', 1)
        # 禁止拉伸
        self.window.resizable(0, 0)
        # 去掉窗口最大化最小化按钮，只保留关闭
        self.window.attributes("-toolwindow", 2)
        # 选择跳转字典
        self.set_jpg_to_dir()

        """绑定事件"""
        # 窗口关闭事件
        self.window.protocol("WM_DELETE_WINDOW", self.exit)

    def exit(self):
        self.root.show()
        self.hide()
